import "./App.css";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import Layout from "./pages/Layout";
import Login from "./pages/Login";
import Pan from "./pages/Pan";
import Index from "./pages/Index";
import PanIndex from "./pages/Pan/components/Index";
import Content from "./pages/Pan/components/Content";
import Bin from "./pages/Pan/components/Bin";

function RequireAuth({ children }) {
  const userInfo = useSelector((state) => state.loginReducer?.userInfo);
  return userInfo?.token ? ( // 判断 localstorage 中登录状态是否为 true
    children
  ) : (
    <Navigate to="/login" replace /> // 跳转到登录
  );
}

function App() {
  const dispatch = useDispatch();
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  if (userInfo?.token) {
    dispatch({ type: "login" });
  }
  return (
    <BrowserRouter>
      <div className="App">
        <Routes>
          <Route path="/" element={<Layout />}>
          <Route index element={<Index />}></Route>
            {/* <Route index element={<Index />}></Route> */}
            <Route
              path="/pan"
              element={
                <RequireAuth>
                  <Pan />
                </RequireAuth>
              }
            >
              <Route index element={<PanIndex />}></Route>
              <Route path="/pan/:path/:subPath" element={<Content />}></Route>
              <Route path="/pan/:path" element={<Bin />}></Route>
            </Route>
            <Route path="/login" element={<Login />}></Route>
          </Route>
        </Routes>
      </div>
    </BrowserRouter>
  );
}

export default App;
